package com.tledu.interceptor;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.tledu.commont.ResultVo;
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class loginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if ("OPTIONS".equalsIgnoreCase(method)) {
            return true;
        }
        String token = request.getHeader("token");
        if (token == null) {
            ResultVo resultVo = new ResultVo(10001, "请先登录", null);
            doResponse(response, resultVo);
        } else {
            try {
                JwtParser parser = Jwts.parser();
                parser.setSigningKey("NoError");
                Jws<Claims> claimsJws = parser.parseClaimsJws(token);
                return true;
            } catch (ExpiredJwtException e) {
                ResultVo resultVo = new ResultVo(10001, "token过期，请重新登录", null);
                doResponse(response, resultVo);
            } catch (UnsupportedJwtException e) {
                ResultVo resultVo = new ResultVo(10001, "token不合法", null);
                doResponse(response, resultVo);
            } catch (Exception e) {
                ResultVo resultVo = new ResultVo(10001, "请先登录", null);
                doResponse(response, resultVo);
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    private void doResponse(HttpServletResponse response, ResultVo resultVo) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        String writeValueAsString = new ObjectMapper().writeValueAsString(resultVo);
        out.print(writeValueAsString);
        out.flush();
        out.close();
    }
}
